package org.ants.basecomponent.action.base;

import org.tinygroup.beancontainer.BeanContainerFactory;
import org.tinygroup.cache.Cache;
import org.tinygroup.vfs.FileObject;
import org.tinygroup.vfs.VFS;

import java.util.HashMap;
import java.util.Map;

/**
 */
public class BaseAction {
    private Cache cache;
    /**
     * 拼装前台Ajax请求结果
     *
     * @param result
     * @param msg
     * @return
     */
    protected Map<String, String> resultMap(boolean result, final String msg) {
        Map<String, String> map = new HashMap<String, String>();
        if (result) {
            map.put("status", "y");
        } else {
            map.put("status", "n");
        }
        map.put("info", msg);
        return map;
    }

    /**
     * 拼装前台Ajax请求结果
     * 返回状态为int类型
     * @param result
     * @param msg
     * @return
     */
    protected Map<?, ?> resultMap(Integer result, final String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", result);
        map.put("info", msg);
        return map;
    }

    protected Cache getCache(){
        if(cache==null){
            cache = BeanContainerFactory.getBeanContainer(BaseAction.class.getClassLoader()).getBean("cacheBean");
        }
        return cache;
    }
    
    protected FileObject getFileObject(String fileName) {

        String path = this.getClass().getResource("").getPath();
        path = path.substring(path.lastIndexOf("file:")+6,path.lastIndexOf(".jar!"))+".jar";
        FileObject fileObject = VFS.resolveFile(path);
        return findFileObject(fileObject, fileName);
    }

    private FileObject findFileObject(FileObject fileObject, String name) {

        if (fileObject.getFileName().equals(name)) {
            return fileObject;
        } else {
            if (fileObject.isFolder() && fileObject.getChildren() != null) {
                for (FileObject fo : fileObject.getChildren()) {
                    FileObject f = findFileObject(fo, name);
                    if (f != null) {
                        return f;
                    }
                }
            }
        }
        return null;
    }
}
